package com.eternal.widget;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import androidx.appcompat.widget.AppCompatTextView;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.util.AttributeSet;

/**
 * @author ling0
 */
public class NoSpaceTextView extends AppCompatTextView {
    private static final int[] COLORS=new int[]{0xff128bec, 0xff1da9f1, 0xff29c9f7};
    private boolean refreshMeasure=true;
    private int paddingTop;
    private ColorSpan span;

    public NoSpaceTextView(Context context) {
        this(context, null);
    }

    public NoSpaceTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NoSpaceTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paddingTop=getPaddingTop();
        span=new ColorSpan(COLORS);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        removeSpace(widthMeasureSpec, heightMeasureSpec);
    }

    public void setText(String text, int[] colors){
        if(colors!=null){
            span=new ColorSpan(colors);
        }
        SpannableString s=new SpannableString(text);
        s.setSpan(span, 0, s.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        setText(s, BufferType.SPANNABLE);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, type);
        refreshMeasure=true;
    }

    private void removeSpace(int widthSpc, int heightSpc){
        int paddingTop;
        String[] texts=getFirstAndLastLines();
        TextPaint paint=getPaint();
        Rect rect=new Rect();
        String text=texts[0];
        paint.getTextBounds(text, 0, text.length(), rect);
        Paint.FontMetricsInt fontMetricsInt=new Paint.FontMetricsInt();
        paint.getFontMetricsInt(fontMetricsInt);
        paddingTop=(fontMetricsInt.top-rect.top);
        setPadding(getPaddingStart(), paddingTop+this.paddingTop,
                getPaddingEnd(), getPaddingBottom());
        text=texts[1];
        paint.getTextBounds(text, 0,text.length(), rect);
        setMeasuredDimension(getMeasuredWidth(),
                getMeasuredHeight()-(fontMetricsInt.bottom-rect.bottom));
        if(refreshMeasure){
            refreshMeasure=false;
            measure(widthSpc, heightSpc);
        }
    }

    private String[] getFirstAndLastLines(){
        String[] texts=new String[2];
        String text=getText().toString();
        Layout layout=getLayout();
        texts[0]=text.substring(0, layout.getLineEnd(0));
        texts[1]=text.substring(layout.getLineStart(layout.getLineCount()-1));
        return texts;
    }
}
